﻿using System;
using System.Collections.Generic;
using System.Text;
using Core.Model;
using Core.Parser.ASN1Parser.Nodes;
using Core.Exceptions;

namespace Core.Parser.ASN1Parser.Builders
{
    internal class StreamBuilder
    {
        internal static Stream Build(TaggedNode node, Group group)
        {
            var stream = new Stream();
            IngredientBuilder.Build(node, stream, group);

            TaggedNode e;

            if ( (e = node[ASN1ContextCodes.C_MULTIPLEX]) != null)
                stream.Multiplex = BuildMultiplex(e, group);
            else
                throw new OpenMhegException("Missing Multiplex");

            if ( ( e = node[ASN1ContextCodes.C_STORAGE]) != null)
                stream.Storage = e.First.BoolValue;

            if ( ( e = node[ASN1ContextCodes.C_LOOPING]) != null)
                stream.Looping = e.First.IntValue;


            return stream;
            
        }

        private static List<Ingredient> BuildMultiplex(TaggedNode node, Group group)
        {
            var multiplex = new List<Ingredient>();
            
            if (node.Size < 1) throw new OpenMhegException("No items in multiplex");

            foreach ( TaggedNode e in node)
            {
                switch (e.Tag)
                {
                    case ASN1ContextCodes.C_AUDIO:
                        multiplex.Add(AudioBuilder.Build(e, group));
                        break;
                    case ASN1ContextCodes.C_VIDEO:
                        multiplex.Add(VideoBuilder.Build(e, group)); 
                        break;
                    case ASN1ContextCodes.C_RTGRAPHICS:
                        throw new OpenMhegException("FIX ME: RTGRAPHIC not supported");
                        break;
                    default:
                        throw new OpenMhegException("Unknown Stream Item");
                }
            }

            return multiplex;
        }

    }
}
